# -*- coding: utf-8 -*-
import hashlib
import random
import string
import time
import uuid
import requests
from bs4 import BeautifulSoup
from lxml.html import Element, tostring
import logging
_logger = logging.getLogger(__name__)


def wechat_pay(openid, amount):
    """微信企业支付到用户"""
    WXPAY_CLIENT_CERT_PATH = "/opt/odoo/einfo_addons/sale_sys/cert/apiclient_cert.pem"
    WXPAY_CLIENT_KEY_PATH = "/opt/odoo/einfo_addons/sale_sys/cert/apiclient_key.pem"

    url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
    APPID = 'wxbedc2aa729016a59'  # 商户APPID
    MCH_ID = '1295279801'  # 商户号
    nonce_str = get_nonce_str()  # 随机字符串 不能超过32位
    partner_trade_no = get_out_trade_no()  # 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有其他字符)
    openid = openid  # 商户appid下，某用户的openid
    check_name = 'NO_CHECK'
    re_user_name = ''
    amount = amount  # 提现金额
    desc = 'Commission withdrawal'  # 备注
    spbill_create_ip = '14.153.200.167'  # 本机ip
    api_key = 'huangshengpingfanzhenyanglouyu11'  # key

    data = {
        'mch_appid': APPID,
        'mchid': MCH_ID,
        'nonce_str': nonce_str,
        'desc': desc,
        'spbill_create_ip': spbill_create_ip,
        'partner_trade_no': partner_trade_no,
        'check_name': check_name,
        'amount': amount,
        'openid': openid,
    }

    data['sign'] = calculate_sign(data, api_key)
    xml_data = bytes.decode(tostring(dict_to_xml_data(data)))
    _logger.info("-------------------------------------")
    _logger.info(WXPAY_CLIENT_CERT_PATH)
    response = requests.post(url=url, data=xml_data, cert=(WXPAY_CLIENT_CERT_PATH, WXPAY_CLIENT_KEY_PATH))
    _logger.info(xml_data)
    if response:
        body = trans_xml_to_dict(response.text)
        if body['result_code'] == 'SUCCESS':
            is_successful = True
            data = {
                'is_successful': is_successful,
                'return_msg': '支付成功',
                'payment_time': body['payment_time'],

            }
            return data  # 支付成功 返回 一个标识状态，成功支付时间
        elif body['result_code'] == 'FAIL':
            is_successful = False
            data = {
                'is_successful': is_successful,
                'return_msg': body['return_msg'],
                'err_code_des': body['err_code_des']
            }
            return data  # 支付失败 返回 失败和原因


def trans_xml_to_dict(xml):
    """将微信支付交互返回的 XML 格式数据转化为 Python Dict 对象"""

    soup = BeautifulSoup(xml, features='xml')
    xml = soup.find('xml')
    if not xml:
        return {}

    # 将 XML 数据转化为 Dict
    data = dict([(item.name, item.text) for item in xml.find_all()])
    return data


def format_url(params, api_key=None):
    """将字典转换成url并排序"""
    url = "&".join(['%s=%s' % (key, params[key]) for key in sorted(params)])
    if api_key:
        url = '%s&key=%s' % (url, api_key)
    return url


def calculate_sign(params, api_key):
    """生成加密的data并将key加入里面"""
    url = format_url(params, api_key)
    return hashlib.md5(url.encode('utf-8')).hexdigest().upper()


def dict_to_xml_data(data):
    """将data转换成xml发送"""
    elem = Element('xml')
    for key, value in data.items():
        child = Element(key)
        child.text = str(value)
        elem.append(child)
    return elem


def get_out_trade_no():
    """生成商户订单号"""
    return time.strftime("%Y%m%d%H%M%S", time.localtime()) + str(uuid.uuid1())[:8]


def get_nonce_str():
    """生成随机字符串"""
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))
